<template>
  <view class="order-detail-container">
    <!-- 导航栏 -->
    <ob-navbar
      title="我的订单"
      :show-back="true"
      :prevent-default-back="true"
      @left-click="handleBack"
    />

    <!-- 订单状态 -->
    <view class="order-status-section">
      <view class="status-icon">
        <text class="status-emoji">{{ getStatusIcon(orderDetail.status) }}</text>
      </view>
      <view class="status-info">
        <text class="status-title">{{ getStatusText(orderDetail.status) }}</text>
        <text class="status-desc">{{ getStatusDesc(orderDetail.status) }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">
        <text class="title-text">订单信息</text>
      </view>
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">订单号：</text>
          <text class="info-value">{{ orderDetail.orderNo }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">下单时间：</text>
          <text class="info-value">{{ formatTime(orderDetail.createdAt) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.completedAt">
          <text class="info-label">完成时间：</text>
          <text class="info-value">{{ formatTime(orderDetail.completedAt) }}</text>
        </view>

        <view class="info-item">
          <text class="info-label">联系电话：</text>
          <text class="info-value">{{ orderDetail.contactPhone || '暂无' }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.contactName">
          <text class="info-label">联系人：</text>
          <text class="info-value">{{ orderDetail.contactName }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.portName || orderDetail.portId">
          <text class="info-label">收货港口：</text>
          <text class="info-value">{{ orderDetail.portName || orderDetail.portId }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.paymentMethod !== undefined && orderDetail.paymentMethod !== null">
          <text class="info-label">支付方式：</text>
          <text class="info-value">{{ getPayMethodText(orderDetail.paymentMethod) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.type !== undefined && orderDetail.type !== null">
          <text class="info-label">订单类型：</text>
          <text class="info-value">{{ getOrderTypeText(orderDetail.type) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.remark">
          <text class="info-label">备注：</text>
          <text class="info-value">{{ orderDetail.remark }}</text>
        </view>
      </view>
    </view>

    <!-- 商品明细 -->
    <view class="products-section" v-if="orderDetail.items && orderDetail.items.length > 0">
      <view class="section-title">
        <text class="title-text">商品明细</text>
      </view>
      <view class="products-list">
        <view
          v-for="(item, index) in orderDetail.items"
          :key="index"
          class="product-item"
        >
          <view class="product-image">
            <image
              :src="item.productImage || '/static/images/default-product.png'"
              class="product-img"
              mode="aspectFill"
            />
          </view>
          <view class="product-info">
            <text class="product-name">{{ item.productName || '商品名称' }}</text>
            <text class="product-spec" v-if="item.specName">{{ item.specName }}</text>
            <view class="product-price-qty">
              <text class="product-price">¥{{ formatPrice(item.price) }}</text>
              <text class="product-qty">x{{ item.quantity }}</text>
            </view>
          </view>
          <view class="product-total">
            <text class="total-price">¥{{ formatPrice(item.price * item.quantity) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 金额信息 -->
    <view class="amount-section">
      <view class="section-title">
        <text class="title-text">订单金额</text>
      </view>
      <view class="amount-list">

        <view class="amount-item total-row">
          <text class="amount-label">订单总额</text>
          <text class="amount-value total">¥{{ formatPrice(orderDetail.totalAmount) }}</text>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section" v-if="showActions">
      <button
        v-if="orderDetail.status === 1"
        class="action-btn primary"
        @click="payOrder"
      >
        立即支付
      </button>
      <button
        v-if="orderDetail.status === 4"
        class="action-btn secondary"
        @click="buyAgain"
      >
        再次购买
      </button>
    </view>

    <!-- 加载组件 -->
    <ob-loading :visible="isLoading" text="加载中..." />
  </view>
</template>

<script setup>
import { ref, computed, inject, onMounted } from "vue";
import orderApi from "../../api/order.js";
import { portApi } from "../../api/port.js";
import { userApi } from "../../api/user.js";
import request from "../../utils/request.js";


// 全局状态
const store = inject("$store");

// 响应式数据
const orderDetail = ref({});
const isLoading = ref(false);
const orderId = ref("");

// 计算属性
const showActions = computed(() => {
  return orderDetail.value.status === 1 || orderDetail.value.status === 4;
});

// 页面加载
onMounted(() => {
  // 从路由参数获取订单ID
  const pages = getCurrentPages();
  const currentPageInfo = pages[pages.length - 1];
  const options = currentPageInfo.options;

  if (options.orderId) {
    orderId.value = options.orderId;
    loadOrderDetail();
  } else {
    uni.showToast({
      title: "订单ID不存在",
      icon: "none",
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 加载订单详情（统一规范字段 + 商品明细）
const loadOrderDetail = async () => {
  try {
    isLoading.value = true;

    // 标准化：提取商品明细
    const extractItems = (raw) => {
      const list = raw.items || raw.orderItems || raw.productList || raw.products || [];
      return (list || []).map((it) => ({
        productId: it.productId ?? it.id,
        productName: it.productName ?? it.name ?? '',
        productImage: it.productImage ?? it.image ?? it.picUrl ?? '',
        specName: it.specName ?? it.spec ?? it.specValueName ?? '',
        price: it.price ?? it.unitPrice ?? it.salePrice ?? 0,
        quantity: it.quantity ?? it.count ?? it.num ?? 1,
      }));
    };

    // 标准化：统一订单字段（兼容多种后端字段）
    const normalizeOrder = (rawOrder) => {
      // 费用来源兼容
      const fee = rawOrder.orderFee || rawOrder.fee || rawOrder.fees || {};
      const nestedPayTotal = fee?.payTotal ?? fee?.pay_total;
      const productTotal = fee?.productTotal ?? rawOrder.productTotal;
      const freight = fee?.freight ?? rawOrder.freight;
      const discount = fee?.discount ?? rawOrder.discount;
      const computedTotal = (productTotal || 0) + (freight || 0) - (discount || 0);
      const total =
        rawOrder.totalAmount ??
        rawOrder.amount ??
        rawOrder.payAmount ??
        rawOrder.totalPrice ??
        nestedPayTotal ??
        computedTotal;

      // 电话来源：订单 -> 地址 -> 全局用户
      const phoneFromOrder =
        rawOrder.captainPhone ??
        rawOrder.contactPhone ??
        (rawOrder.address && rawOrder.address.mobile);
      const phoneFromStore = store?.state?.userInfo?.phone;

      return {
        id: rawOrder.orderId ?? rawOrder.id,
        orderNo: rawOrder.orderNo ?? rawOrder.number ?? rawOrder.orderCode,
        status: rawOrder.orderStatus ?? rawOrder.status,
        totalAmount: total,
        createdAt: rawOrder.createTime ?? rawOrder.createdAt ?? rawOrder.createDate,
        completedAt: rawOrder.completedTime ?? rawOrder.finishTime ?? rawOrder.completedAt,
        shippedAt: rawOrder.shippedTime ?? rawOrder.deliveryTime,
        confirmedAt: rawOrder.confirmedTime ?? rawOrder.confirmTime,
        shippingAddress:
          rawOrder.shippingAddress ||
          (rawOrder.address && (rawOrder.address.fullAddress || rawOrder.address.detail)) ||
          rawOrder.addressText,
        contactPhone: phoneFromOrder ?? phoneFromStore ?? '',
        contactName: rawOrder.captainName ?? rawOrder.contactName ?? (rawOrder.address && rawOrder.address.name),
        portName: rawOrder.portName ?? (rawOrder.port && rawOrder.port.name),
        portId: rawOrder.portId ?? (rawOrder.port && rawOrder.port.id),
        type: rawOrder.type ?? rawOrder.orderType,
        paymentMethod: rawOrder.paymentMethod ?? rawOrder.payMethod ?? rawOrder.paymentType,
        remark: rawOrder.remark || '',
        items: extractItems(rawOrder),
      };
    };

    const response = await orderApi.getOrderDetailUnified(orderId.value);

    if (response && response.order) {
      orderDetail.value = normalizeOrder(response.order);
    } else if (response && response.data && response.data.order) {
      orderDetail.value = normalizeOrder(response.data.order);
    } else if (response) {
      orderDetail.value = normalizeOrder(response);
    }

    await loadContactPhoneIfNeeded();

    // 若缺少港口名称但有ID，则补充查询名称
    await loadPortNameIfNeeded();
  } catch (error) {
    console.error('加载订单详情失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    });
  } finally {
    isLoading.value = false;
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "暂无";

  const date = new Date(timestamp);
  const timeStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")} ${String(
    date.getHours()
  ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;

  return timeStr;
};

// 格式化价格


const loadPortNameIfNeeded = async () => {
  try {
    const hasName = !!(orderDetail.value && orderDetail.value.portName)
    const hasId = !!(orderDetail.value && orderDetail.value.portId)
    if (hasId && !hasName) {
      const pid = orderDetail.value.portId
      const resp = await portApi.getIndexPortDetail(pid)
      const name = resp?.data?.port?.name || resp?.port?.name || resp?.data?.name || resp?.name
      if (name) {
        orderDetail.value = { ...orderDetail.value, portName: name }
      }
    }

  } catch (e) {
    console.warn('获取港口名称失败（忽略）:', e)
  }
}

const formatPrice = (price) => {
  if (!price) return "0.00";
  return Number(price).toFixed(2);
};

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    1: "💰", // 待付款
    2: "📦", // 配货中
    4: "✅", // 已完成
    5: "❌", // 已取消
  };
  return iconMap[status] || "📋";
};


// 若订单数据未包含联系电话，则尝试从用户资料补充（确认订单页的默认值同样来自用户资料）
const loadContactPhoneIfNeeded = async () => {
  try {
    const v = orderDetail.value
    const hasPhone = !!(v && v.contactPhone)
    if (!hasPhone) {
      const resp = await userApi.getUserProfile()
      const phone = resp?.phone || resp?.data?.phone || resp?.user?.phone
      if (phone) {
        orderDetail.value = { ...v, contactPhone: String(phone) }
      }
    }
  } catch (e) {
    console.warn('获取用户联系电话失败（忽略）:', e?.message || e)
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    1: "待付款", // 数据库状态1
    2: "配货中", // 数据库状态2
    3: "送货中", // 数据库状态3
    4: "已完成", // 数据库状态4
    5: "已取消", // 数据库状态5
  };
  return textMap[status] || "未知状态";
};

// 支付方式展示文案（统一转换显示，兼容数值与字符串）
const getPayMethodText = (v) => {
  const key = (v === 1 || v === '1') ? '1'
    : (v === 2 || v === '2') ? '2'
    : (v === 3 || v === '3') ? '3'
    : String(v || '').toLowerCase()

  const map = {
    // 数值型（后端：1-在线支付;2-现金支付;3-公司支付）
    '1': '在线支付',
    '2': '现金支付',
    '3': '公司支付',
    // 字符串型（前端：wechat/alipay/bank/cash 等）
    wechat: '微信支付',
    wechat_pay: '微信支付',
    wxpay: '微信支付',
    alipay: '支付宝',
    bank: '银行转账',
    cash: '现金',
    online: '在线支付',
    company: '公司支付',
  }
  return map[key] || '—'
};

// 订单类型文案（兼容数值与字符串）
const getOrderTypeText = (v) => {
  const key = (v === 1 || v === '1') ? '1' : (v === 2 || v === '2') ? '2' : String(v || '').toLowerCase()
  const map = {
    '1': '个人订单',
    '2': '船舶订单',
    personal: '个人订单',
    ship: '船舶订单',
  }
  return map[key] || '—'
};


// 获取状态描述
const getStatusDesc = (status) => {
  const descMap = {
    1: "请尽快完成支付",
    2: "我们正在为您准备商品",
    4: "订单已完成，感谢您的购买",
    5: "订单已取消",
  };
  return descMap[status] || "";
};

// 支付订单
const payOrder = () => {
  uni.showModal({
    title: "支付订单",
    content: "确定要支付此订单吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: "正在创建支付...",
            mask: true,
          });

          // 调用支付宝支付接口
          const paymentResponse = await request.post('/user/alipay/create', {
            orderNo: orderDetail.value.orderNo,
            amount: orderDetail.value.totalAmount.toString(),
            subject: '海关商品支付'
          });

          uni.hideLoading();

          if (paymentResponse) {
            // 支付宝返回的是HTML表单，在当前页面显示支付表单
            const paymentForm = paymentResponse;
            
            // 创建一个临时的div容器来显示支付表单
            const paymentContainer = document.createElement('div');
            paymentContainer.innerHTML = paymentForm;
            paymentContainer.style.position = 'fixed';
            paymentContainer.style.top = '0';
            paymentContainer.style.left = '0';
            paymentContainer.style.width = '100%';
            paymentContainer.style.height = '100%';
            paymentContainer.style.zIndex = '9999';
            paymentContainer.style.backgroundColor = 'white';
            document.body.appendChild(paymentContainer);
            
            // 自动提交支付表单
            const form = paymentContainer.querySelector('form');
            if (form) {
              form.submit();
            }
          } else {
            console.error('支付创建失败:', paymentResponse);
            uni.showToast({
              title: '支付创建失败',
              icon: 'error'
            });
          }
        } catch (paymentError) {
          uni.hideLoading();
          console.error('调用支付接口失败:', paymentError);
          uni.showToast({
            title: paymentError.message || '支付调用失败',
            icon: 'error'
          });
        }
      }
    },
  });
};

// 再次购买
const buyAgain = async () => {
  uni.showModal({
    title: "再次购买",
    content: "确定要再次购买此订单中的商品吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: "处理中...",
            mask: true,
          });

          // 调用再次购买API
          await orderApi.reorder(orderId.value);

          uni.hideLoading();
          uni.showToast({
            title: "已添加到购物车",
            icon: "success",
          });

          // 跳转到购物车页面
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/cart/index",
              fail: () => {
                // 如果购物车页面不存在，跳转到首页
                uni.switchTab({
                  url: "/pages/index/index",
                });
              },
            });
          }, 1500);
        } catch (error) {
          uni.hideLoading();
          console.error("再次购买失败:", error);
          uni.showToast({
            title: error.message || "操作失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 处理返回按钮 - 针对Hash路由环境优化
const handleBack = () => {
  // 获取URL参数中的来源信息
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  const from = options.from

  console.log('订单详情返回按钮点击，来源:', from, '页面栈长度:', pages.length)

  // 优先使用URL参数指定的来源
  if (from) {
    handleBackBySource(from)
    return
  }

  // 在Web环境下，优先使用浏览器的历史记录返回
  // #ifdef H5
  if (window.history.length > 1) {
    window.history.back();
  } else {
    // 如果没有历史记录，跳转到订单列表
    uni.navigateTo({
      url: "/pages/order/list"
    });
  }
  // #endif

  // 在非H5环境下使用uni-app的返回方法
  // #ifndef H5
  uni.navigateBack({
    delta: 1,
    fail: () => {
      // 如果返回失败，跳转到订单列表
      uni.navigateTo({
        url: "/pages/order/list",
        fail: () => {
          // 如果订单列表页面不存在，跳转到个人中心
          uni.switchTab({
            url: "/pages/profile/index",
          });
        },
      });
    },
  });
  // #endif
};

// 根据来源参数处理返回
const handleBackBySource = (from) => {
  console.log('根据来源参数返回:', from)

  switch (from) {
    case 'order':
      // 从订单列表来的，返回订单列表
      uni.navigateTo({
        url: '/pages/order/list'
      })
      break
    case 'profile':
      // 从个人中心来的，返回个人中心
      uni.switchTab({
        url: '/pages/profile/index'
      })
      break
    default:
      // 未知来源，返回订单列表
      uni.navigateTo({
        url: "/pages/order/list",
        fail: () => {
          // 如果订单列表页面不存在，跳转到个人中心
          uni.switchTab({
            url: "/pages/profile/index",
          });
        },
      });
      break
  }
};
</script>

<style lang="scss" scoped>
.order-detail-container {
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.order-status-section {
  background: #ffffff;
  padding: 30px 20px;
  margin: 15px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 20px;
}

.status-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--primary-color), #0ea5e9);
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-emoji {
  font-size: 24px;
}

.status-info {
  flex: 1;
}

.status-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  display: block;
  margin-bottom: 5px;
}

.status-desc {
  font-size: 14px;
  color: #64748b;
}

.order-info-section,
.amount-section {
  background: #ffffff;
  margin: 0 15px 15px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.section-title {
  padding: 20px 20px 15px;
  border-bottom: 1px solid #f1f5f9;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.info-list,
.amount-list {
  padding: 15px 20px 20px;
}

.info-item,
.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label,
.amount-label {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  min-width: 80px;
}

.info-value {
  font-size: 14px;
  color: #1e293b;
  text-align: right;
  flex: 1;
  margin-left: 10px;
  word-break: break-all;
}

.amount-value {
  font-size: 16px;
  color: #ef4444;
  font-weight: 600;
}

.action-section {
  padding: 20px 15px;
  margin-top: auto;
}


/* 商品明细样式 */
.products-section {
  background: #ffffff;
  margin: 0 15px 15px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}
.products-list { padding: 15px 20px 20px; }
.product-item { display: flex; align-items: center; gap: 12px; padding: 10px 0; border-bottom: 1px solid #f1f5f9; }
.product-item:last-child { border-bottom: none; }
.product-image { width: 60px; height: 60px; flex: 0 0 60px; }
.product-img { width: 60px; height: 60px; border-radius: 8px; background: #f8fafc; }
.product-info { flex: 1; display: flex; flex-direction: column; gap: 6px; }
.product-name { font-size: 14px; color: #1e293b; font-weight: 600; }
.product-spec { font-size: 12px; color: #94a3b8; }
.product-price-qty { display: flex; gap: 8px; align-items: center; }
.product-price { color: #ef4444; font-weight: 600; }
.product-qty { color: #64748b; }
.product-total { min-width: 80px; text-align: right; font-weight: 600; color: #1e293b; }


.action-btn {
  width: 100%;
  height: 50px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  border: none;
  margin-bottom: 10px;
  transition: all 0.3s ease;

  &.primary {
    background: linear-gradient(135deg, var(--primary-color), #0ea5e9);
    color: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

    &:active {
      transform: scale(0.98);
    }
  }

  &.secondary {
    background: #f8fafc;
    color: #64748b;
    border: 1px solid #e2e8f0;

    &:active {
      background: #f1f5f9;
    }
  }

  &:last-child {
    margin-bottom: 0;
  }
}
</style>
